<template>
  <div class="feed-container">
    <!-- 顶部导航 -->
    <div class="top-nav">
      <div class="nav-center">
        <div class="tab" :class="{ active: activeTab === 'recommend' }" @click="switchTab('recommend')">
          推荐
        </div>
        <div class="tab" :class="{ active: activeTab === 'following' }" @click="switchTab('following')">
          关注
        </div>
      </div>
    </div>

    <!-- 视频列表 -->
    <div class="video-list" ref="videoList" @scroll="handleScroll">
      <div v-for="(video, index) in videos" :key="video.id" class="video-item"
        :class="{ active: currentIndex === index }" :ref="`video-${index}`">
        <!-- 视频容器 -->
        <div class="video-wrapper">
          <video :ref="`player-${index}`" :src="video.play_url" :poster="video.cover_url" class="video-player"
            :muted="isMuted" loop playsinline webkit-playsinline @loadedmetadata="onVideoLoaded(index)"
            @click="togglePlayPause(index)"></video>

          <!-- 加载中 -->
          <div v-if="video.loading" class="video-loading">
            <div class="loading-spinner">⏳</div>
            <p>加载中...</p>
          </div>

          <!-- 播放按钮 -->
          <div v-if="video.paused" class="play-button" @click="togglePlayPause(index)">
            ▶️
          </div>
        </div>

        <!-- 右侧操作栏 -->
        <div class="action-bar">
          <!-- 头像 -->
          <div class="avatar">
            <img :src="video.author.avatar || defaultAvatar" :alt="video.author.name" />
          </div>

          <!-- 点赞 -->
          <div class="action-item" @click="toggleLike(video)">
            <div class="action-icon" :class="{ liked: video.is_favorite }">
              {{ video.is_favorite ? '❤️' : '🤍' }}
            </div>
            <span class="action-count">{{ formatCount(video.favorite_count) }}</span>
          </div>
        </div>

        <!-- 底部信息 -->
        <div class="video-info">
          <div class="author-info">
            <span class="author-name">@{{ video.author.name }}</span>
          </div>
          <div class="video-title">{{ video.title }}</div>
        </div>
      </div>
    </div>

    <!-- 底部导航 -->
    <div class="bottom-nav">
      <div class="nav-item active" @click="goToFeed">
        <span class="nav-icon">🏠</span>
        <span class="nav-text">首页</span>
      </div>
      <div class="nav-item" @click="goToPublish">
        <span class="nav-icon">➕</span>
        <span class="nav-text">发布</span>
      </div>
      <div class="nav-item" @click="goToLog">
        <span class="nav-icon">📜</span>
        <span class="nav-text">日志</span>
      </div>
      <div class="nav-item" @click="goToProfile">
        <span class="nav-icon">👤</span>
        <span class="nav-text">我的</span>
      </div>

    </div>

    <!-- 静音控制 -->
    <div class="mute-control" @click="toggleMute">
      {{ isMuted ? '🔇' : '🔊' }}
    </div>
  </div>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'Feed',
  data() {
    return {
      videos: [],
      currentIndex: 0,
      activeTab: 'recommend',
      isMuted: true,
      isLoading: false,
      hasMore: true,
      defaultAvatar: require('@/assets/avatar.png')
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'isLoggedIn'])
  },
  async mounted() {
    await this.loadVideos()
    this.initVideoPlayer()
    this.bindScrollEvents()
  },
  beforeDestroy() {
    this.pauseAllVideos()
  },
  methods: {
    ...mapActions(['fetchVideos', 'toggleFavorite']),

    async loadVideos(refresh = false) {
      if (this.isLoading) return

      this.isLoading = true
      try {
        const filteredVideos = await this.fetchVideos()

        if (refresh) {
          this.videos = filteredVideos
          this.currentIndex = 0
        } else {
          this.videos.push(...filteredVideos)
        }

        // 初始化视频状态
        filteredVideos.forEach(video => {
          this.$set(video, 'loading', true)
          this.$set(video, 'paused', true)
        })

        this.hasMore = filteredVideos.length > 0
      } catch (error) {
        console.error('加载视频失败:', error)
        this.$message.error('加载视频失败')
      } finally {
        this.isLoading = false
      }
    },

    initVideoPlayer() {
      this.$nextTick(() => {
        if (this.videos.length > 0) {
          this.playVideo(0)
        }
      })
    },

    onVideoLoaded(index) {
      if (this.videos[index]) {
        this.$set(this.videos[index], 'loading', false)
        if (index === this.currentIndex) {
          this.playVideo(index)
        }
      }
    },

    playVideo(index) {
      this.pauseAllVideos()
      const video = this.$refs[`player-${index}`] && this.$refs[`player-${index}`][0]
      if (video && this.videos[index]) {
        video.currentTime = 0
        video.play().catch(e => console.log('播放失败:', e))
        this.$set(this.videos[index], 'paused', false)
      }
    },

    pauseAllVideos() {
      this.videos.forEach((video, index) => {
        const player = this.$refs[`player-${index}`] && this.$refs[`player-${index}`][0]
        if (player) {
          player.pause()
          this.$set(video, 'paused', true)
        }
      })
    },

    togglePlayPause(index) {
      const video = this.$refs[`player-${index}`] && this.$refs[`player-${index}`][0]
      const videoData = this.videos[index]

      if (video && videoData) {
        if (video.paused) {
          this.playVideo(index)
        } else {
          video.pause()
          this.$set(videoData, 'paused', true)
        }
      }
    },

    handleScroll() {
      const container = this.$refs.videoList
      if (!container) return

      const containerHeight = container.clientHeight
      const scrollTop = container.scrollTop

      // 计算当前视频索引
      const videoHeight = containerHeight
      const newIndex = Math.round(scrollTop / videoHeight)

      if (newIndex !== this.currentIndex && newIndex < this.videos.length) {
        this.currentIndex = newIndex
        this.playVideo(newIndex)
      }

      // 检查是否需要加载更多
      if (scrollTop + containerHeight >= container.scrollHeight - 1000) {
        this.loadMoreVideos()
      }
    },

    async loadMoreVideos() {
      if (!this.hasMore || this.isLoading) return
      await this.loadVideos(false)
    },

    async toggleLike(video) {
      if (!this.isLoggedIn) {
        this.$message.warning('请先登录')
        this.$router.push('/login')
        return
      }

      try {
        // 先记录原始状态
        const originalFavorite = video.is_favorite;
        const originalCount = video.favorite_count || 0;

        console.log('Feed页面点赞前状态 - 视频ID:', video.id, '已点赞:', originalFavorite, '点赞数:', originalCount);

        // 乐观更新UI
        this.$set(video, 'is_favorite', !originalFavorite);
        const newCount = originalCount + (originalFavorite ? -1 : 1);
        this.$set(video, 'favorite_count', newCount);

        console.log('Feed页面点赞后状态 - 视频ID:', video.id, '已点赞:', !originalFavorite, '点赞数:', newCount);

        // 然后发送API请求
        await this.toggleFavorite({
          videoId: video.id.toString(),
          actionType: originalFavorite ? 2 : 1 // 1: 点赞, 2: 取消点赞
        });

        console.log('Feed页面API请求完成后 - 视频ID:', video.id, '已点赞:', video.is_favorite, '点赞数:', video.favorite_count);

      } catch (error) {
        console.error('点赞失败:', error);
        // 发生错误时恢复UI状态
        const isFavorite = video.is_favorite;
        this.$set(video, 'is_favorite', !isFavorite);
        this.$set(
          video,
          'favorite_count',
          (video.favorite_count || 0) + (isFavorite ? -1 : 1)
        );
        this.$message.error('操作失败');
      }
    },

    toggleMute() {
      this.isMuted = !this.isMuted
      // 应用到所有视频
      this.videos.forEach((_, index) => {
        const video = this.$refs[`player-${index}`] && this.$refs[`player-${index}`][0]
        if (video) {
          video.muted = this.isMuted
        }
      })
    },

    switchTab(tab) {
      this.activeTab = tab
      this.loadVideos(true)
    },

    // 格式化数字
    formatCount(count) {
      if (!count) return '0'
      if (count < 1000) return count.toString()
      if (count < 10000) return (count / 1000).toFixed(1) + 'k'
      return (count / 10000).toFixed(1) + 'w'
    },

    // 导航方法
    goToFeed() { /* 当前页面 */ },
    goToPublish() { this.$router.push('/publish') },
    goToProfile() { this.$router.push('/profile') },
    goToLog() { this.$router.push('/log') },

    bindScrollEvents() {
      const container = this.$refs.videoList
      if (container) {
        // 禁用默认滚动行为，使用自定义滚动
        container.addEventListener('touchstart', this.handleTouchStart, { passive: false })
        container.addEventListener('touchmove', this.handleTouchMove, { passive: false })
      }
    },

    handleTouchStart(e) {
      this.startY = e.touches[0].clientY
    },

    handleTouchMove(e) {
      // 阻止默认滚动，实现自定义滑动效果
      e.preventDefault()
    }
  }
}
</script>

<style scoped>
.feed-container {
  width: 100%;
  height: 100vh;
  background: #000;
  position: relative;
  overflow: hidden;
}

.top-nav {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: linear-gradient(180deg, rgba(0, 0, 0, 0.5) 0%, transparent 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 15px;
  z-index: 100;
  color: white;
}

.nav-center {
  display: flex;
  gap: 20px;
}

.tab {
  padding: 8px 16px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
}

.tab.active {
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10px);
}

.video-list {
  height: 100vh;
  overflow-y: auto;
  scroll-snap-type: y mandatory;
  -webkit-overflow-scrolling: touch;
}

.video-list::-webkit-scrollbar {
  display: none;
}

.video-item {
  width: 100%;
  height: 100vh;
  position: relative;
  scroll-snap-align: start;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.video-player {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
  object-fit: contain;
  cursor: pointer;
}

.video-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: white;
}

.loading-spinner {
  font-size: 30px;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

.play-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80px;
  height: 80px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
  cursor: pointer;
  backdrop-filter: blur(10px);
  color: white;
}

.action-bar {
  position: absolute;
  right: 15px;
  bottom: 120px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  align-items: center;
  z-index: 5;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  border: 2px solid white;
  overflow: hidden;
  position: relative;
  cursor: pointer;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  color: white;
}

.action-icon {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.action-icon.liked {
  background: rgba(255, 45, 85, 0.2);
  transform: scale(1.1);
}

.action-count {
  font-size: 12px;
  font-weight: 500;
}

.video-info {
  position: absolute;
  left: 15px;
  bottom: 120px;
  right: 80px;
  color: white;
  z-index: 5;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
  padding: 20px 10px 10px 10px;
  border-radius: 8px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.author-name {
  font-weight: bold;
  font-size: 16px;
}

.video-title {
  font-size: 14px;
  line-height: 1.4;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.bottom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(20px);
  display: flex;
  justify-content: space-around;
  align-items: center;
  z-index: 100;
  max-width: 375px;
  margin: 0 auto;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  color: rgba(255, 255, 255, 0.7);
  transition: all 0.3s ease;
  padding: 6px 12px;
  min-width: 60px;
  text-align: center;
}

.nav-item:hover {
  color: white;
  transform: translateY(-1px);
}

.nav-item.active {
  color: #ff2d55;
}

.nav-icon {
  font-size: 18px;
  margin-bottom: 3px;
  line-height: 1;
}

.nav-text {
  font-size: 10px;
  font-weight: 500;
  line-height: 1;
}

.mute-control {
  position: fixed;
  top: 60px;
  right: 15px;
  width: 40px;
  height: 40px;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 18px;
  z-index: 99;
  backdrop-filter: blur(10px);
}

/* 移动端优化 */
@media (max-width: 480px) {
  .video-info {
    left: 10px;
    right: 70px;
    bottom: 80px;
    padding: 15px 8px 8px 8px;
  }

  .action-bar {
    right: 10px;
    bottom: 80px;
    gap: 12px;
  }

  .action-icon {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }

  .avatar {
    width: 45px;
    height: 45px;
  }

  .bottom-nav {
    height: 50px;
    padding: 0 5px;
  }

  .nav-item {
    padding: 4px 6px;
    min-width: 45px;
  }

  .nav-icon {
    font-size: 16px;
    margin-bottom: 2px;
  }

  .nav-text {
    font-size: 9px;
  }

  /* 横屏手机的特殊处理 */
  @media (orientation: landscape) {
    .video-player {
      max-width: 95%;
      /* 在横屏模式下稍微减小最大宽度，留出边距 */
    }

    .action-bar {
      bottom: 50px;
      right: 5px;
    }

    .video-info {
      bottom: 50px;
      left: 5px;
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>